package com.zelin.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.zelin.common.constant.ProductConstant;
import com.zelin.common.to.SkuReDuctionTo;
import com.zelin.common.to.SpuBoundsTo;
import com.zelin.common.to.es.SkuEsModel;
import com.zelin.common.to.es.SkuHasStockVo;
import com.zelin.common.utils.R;
import com.zelin.gulimall.product.entity.*;
import com.zelin.gulimall.product.feign.CouponFeignService;
import com.zelin.gulimall.product.feign.SearchFeignService;
import com.zelin.gulimall.product.feign.WareFeignService;
import com.zelin.gulimall.product.service.*;
import com.zelin.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zelin.common.utils.PageUtils;
import com.zelin.common.utils.Query;

import com.zelin.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SearchFeignService searchFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //1.保存spu组合信息
    @Transactional
    @Override
    public void saveSpuVo(SpuSaveVo vo) {
        //1.1)保存到pms_spu_info表中
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //1.2)保存数据到pms_spu_info_desc表中
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",vo.getDecript()));
        spuInfoDescService.save(spuInfoDescEntity);

        //1.3)保存数据到pms_spu_images表中
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        //1.4)保存到pms_product_attr_value表中
        attrValueService.saveProductAttrValue(spuInfoEntity.getId(),vo.getBaseAttrs());

        //1.5)下面开始保存sku信息

        List<Skus> skus = vo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach(sku->{
                String defaultImage = "";
                for (Images image : sku.getImages()) {
                   if(1 == image.getDefaultImg()){
                       defaultImage = image.getImgUrl();
                   }
                }
                SkuInfoEntity entity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, entity);
                entity.setBrandId(spuInfoEntity.getBrandId());
                entity.setCatalogId(spuInfoEntity.getCatalogId());
                entity.setSaleCount(0L);
                entity.setSpuId(spuInfoEntity.getId());
                entity.setSkuDefaultImg(defaultImage);
                //1.5.1)保存到pms_sku_info表中
                skuInfoService.save(entity);


                //1.5.2)保存到pms_spu_images表中
                List<SkuImagesEntity> skuImageEntities = sku.getImages().stream().map(m->{
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setImgUrl(m.getImgUrl());
                    imagesEntity.setDefaultImg(m.getDefaultImg());
                    imagesEntity.setSkuId(entity.getSkuId());
                    return imagesEntity;
                }).filter(f-> StringUtils.isNotBlank(f.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImageEntities);

                //1.5.3)保存到pms_sku_sale_attr_value表中
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> attrValueEntities = attr.stream().map(m -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(m, attrValueEntity);
                    attrValueEntity.setSkuId(entity.getSkuId());
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValueEntities);

                //1.5.4)保存spu的积分信息`sms_spu_bounds`
                SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
                Bounds bounds = vo.getBounds();
                BeanUtils.copyProperties(bounds,spuBoundsTo);
                spuBoundsTo.setSpuId(spuInfoEntity.getId());
                R r = couponFeignService.saveSpuBounds(spuBoundsTo);
                if(r.getCode() != 0){
                    log.error("远程保存spu积分信息失败！");
                }

                //1.5.4)sku的优惠、满减信息：gulimall_sms-》`sms_sku_full_reduction/`sms_sku_ladder`/`sms_member_price`
                SkuReDuctionTo skuReDuctionTo = new SkuReDuctionTo();
                BeanUtils.copyProperties(sku,skuReDuctionTo);
                skuReDuctionTo.setSkuId(entity.getSkuId());
                if(skuReDuctionTo.getFullCount() > 0 || skuReDuctionTo.getFullPrice().doubleValue() > 0){
                    R r1 = couponFeignService.saveSkuReduction(skuReDuctionTo);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败！");
                    }
                }

            });
        }

    }

    //进行spu信息的条件查询
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        //1.得到分页对象
        IPage<SpuInfoEntity> ipage = new Query<SpuInfoEntity>().getPage(params);
        //2.定义查询对象
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();
        //3.进行条件判断
        /**
         * status: 1
         * key:
         * brandId: 2
         * catelogId: 225
         */
        if(params != null && params.size() > 0){
            String key = (String) params.get("key");
            String status = (String) params.get("status");
            String brandId = (String) params.get("brandId");
            String catelogId = (String) params.get("catelogId");
            //关键字判断
            if(StringUtils.isNotBlank(key)){
                wrapper.and(w->{
                    w.eq("id",key).or().like("spu_name",key);
                });
            }
            //状态值判断
            if(StringUtils.isNotBlank(status) && !"0".equalsIgnoreCase(status)){
                wrapper.eq("publish_status",status);
            }
            //品牌id判断
            if(StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)){

                wrapper.eq("brand_id",brandId);
            }
            //分类id判断
            if(StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(catelogId)){
                wrapper.eq("catalog_id",catelogId);
            }

        }
        IPage<SpuInfoEntity> page = this.page(ipage, wrapper);

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     * 主要思想：根据spuId，查询出与索引库字段相匹配的数据并放到索引库中
     */
    @Override
    @Transactional
    public void up(Long spuId) {
        //1.根据spuId查询出所有的sku商品列表
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        //1.1)找到skuId的列表
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //2.根据spuId得到ProductAttrValueEntity集合
        List<ProductAttrValueEntity> productAttrValueEntities = attrValueService.getAttrIdsBySpuId(spuId);

        //3.处理集合为attrId集合
        List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());


        //4.在pms_attr表中查询搜索类型为1（代表可检索）的attr_id的属性列表
        List<Long> searchAttrIds = attrService.getAttrIdsBySelectType(attrIds);

        //5.从productAttrValueEntities集合中筛选出attrId在searchAttrIds中的元素并设置SkuEsModel.attrs集合
        List<SkuEsModel.Attr> attrs = productAttrValueEntities.stream()
                .filter(f -> searchAttrIds.contains(f.getAttrId()))
                .map(m -> {
                    SkuEsModel.Attr attr = new SkuEsModel.Attr();
                    BeanUtils.copyProperties(m, attr);
                    return attr;
                }).collect(Collectors.toList());

        //6.处理SkuEsModel中的hasstock字段
        R r = wareFeignService.hasStock(skuIds);
        TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
        };
        //7.得到一个map，key为skuId,值为boolean值，代表是否有库存
        Map<Long, Boolean> map = null;
        try{
            map = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常:原因{}",e);
        }
        //8.组装需要的数据
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(m -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(m, skuEsModel);
            skuEsModel.setSkuPrice(m.getPrice());
            skuEsModel.setSkuImg(m.getSkuDefaultImg());
            //设置库存信息
            if (finalMap == null) {
                skuEsModel.setHasStock(false);
            } else {
                skuEsModel.setHasStock(finalMap.get(m.getSkuId()));
            }
            //TODO 2、热度评分。0
            skuEsModel.setHotScore(0L);
            //设置品牌名称
            BrandEntity brand = brandService.getById(m.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            //设置分类名称
            skuEsModel.setCatalogName(categoryService.getById(m.getCatalogId()).getName());
            //设置串图片
            skuEsModel.setBrandImg(brand.getLogo());
            //设置检索属性
            skuEsModel.setAttrs(attrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        System.out.println("skuEsModels = " + skuEsModels);

        //9.调用gulimall-search微服务发送请求
        R saveR = searchFeignService.save(skuEsModels);
        if(saveR.getCode() == 0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            log.error("远程保存ES失败！");
        }

    }


}
